package fr.gmdev.mail.fonction.mailet;

import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.mail.MessagingException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMessage.RecipientType;

import org.apache.mailet.Mail;
import org.apache.mailet.MailetConfig;
import org.apache.mailet.base.GenericMailet;

import fr.gmdev.mail.fonction.core.LocalWorkFlowManager;
import fr.gmdev.mail.fonction.mail.SMTPManager;
import fr.gmdev.mail.fonction.sms.OvhSMSManager;
import fr.gmdev.mail.fonction.sms.SMSManager;
import fr.gmdev.mail.mailet.activity.ActivityLogger;
import fr.gmdev.mail.util.ApplicationParameters;
import fr.gmdev.mail.util.MailetLogger;



public class MailetGmdev extends GenericMailet implements MailetLogger{
	
	public static final String ADMIN = "admin@gmx-workflow.com";
	/* a mettre dans le fichier  mailetcontainer.xml dans la section <processor state="transport".... 
	 * 	<mailet match="All" class="fr.gmdev.mail.fonction.mailet.MailetGmdev" >
	*	  <ads-server-name>localhost</ads-server-name>
	*	  <ads-server-port>8080</ads-server-port>
	*	  <ads-uri>/jdc/seam/resource/rest/mail</ads-uri>
	*   </mailet>
	 */

	// nom dans la configuration des mailet (tag ds xml mailetcontainer.xml pour la mailet MailetADS)
	private static final String SERVER_PORT = "ads-server-port";
	private static final String SERVER_NAME = "ads-server-name";
	private static final String URI = "ads-uri";
	private static final String LOG_FOLDER = "ads-log-folder";
	private static final String LOG_SIZE = "ads-log-size";
	private static final String SAVE_MESSAGES = "ads-save-messages";

	private LocalWorkFlowManager wfm;
	
	private String server = "localhost" ;
	
	private int serverPort = 25;
	
	private String adsUri = "/jdc/seam/resource/rest/mail";
	
	private boolean saveMessages = true;
	
	private SMTPManager smtpManager ;
	
	private SMSManager smsManager;
	
//	private ClientWSDepot clientDepot;
	
	private ActivityLogger activityLogger;
	
	private SimpleDateFormat sdf = new SimpleDateFormat("dd MMMM yyyy à hh:mm");
	
	
	@Override
	public String getMailetInfo() {
		return "MailetADS";
	}



	@Override
	public void init(MailetConfig newConfig) throws MessagingException {
		super.init(newConfig);
		// surcharge de la config par defaut
		if (newConfig.getInitParameter(SERVER_NAME) != null){
			server = newConfig.getInitParameter(SERVER_NAME);
			log("chargement de la configuration " + SERVER_NAME + ":" + server);
		}
		
		if (newConfig.getInitParameter(SERVER_PORT) != null){
			serverPort = Integer.valueOf(newConfig.getInitParameter(SERVER_PORT));
			log("chargement de la configuration " + SERVER_PORT + ":" + serverPort);
		}
		
		if (newConfig.getInitParameter(URI)!=null){
			adsUri= newConfig.getInitParameter(URI);
			log("chargement de la configuration " + URI + ":" + adsUri);
		}
		
		if (newConfig.getInitParameter(SAVE_MESSAGES)!=null){
			saveMessages= Boolean.valueOf(newConfig.getInitParameter(SAVE_MESSAGES));
			log("chargement de la configuration " + SAVE_MESSAGES + ":" + adsUri);
		}
		
		String logFolder = null ;
		int logSize = 1024*1024*1024; // 1 Mo
		if (newConfig.getInitParameter(LOG_FOLDER)!=null){
			logFolder= newConfig.getInitParameter(LOG_FOLDER);
			log("chargement de la configuration " + LOG_FOLDER + ":" + logFolder);
		}
		if (newConfig.getInitParameter(LOG_SIZE)!=null){
			logSize= Integer.valueOf( newConfig.getInitParameter(LOG_SIZE));
			log("chargement de la configuration " + LOG_SIZE + ":" + logSize);
		}
		
//		activityLogger = new ActivityLogger(logFolder, logSize);
		log("creation mail store sur serveur : " + server +":"+serverPort );
		smtpManager = new SMTPManager(server, serverPort);

//		clientDepot = new ClientWSDepot(adsServer, adsServerPort, adsUri);
		
		smsManager = new OvhSMSManager();
		smsManager.setAuthentification(
				ApplicationParameters.getSmsAccount(), 
				ApplicationParameters.getSmsLogin(), 
				ApplicationParameters.getSmsPassword());
		
		wfm = new LocalWorkFlowManager(smtpManager, smsManager);
	}



	@Override
	public void service(Mail mail) throws MessagingException {
		
//		log(adsServer + ":"+ adsServerPort + adsUri);
		
//		log("============> mail recut: " + mail.getName() + "  " + mail.getSender() );
		try {
			MimeMessage msg = mail.getMessage();
			
			String logMsg = "[" + msg.getFrom()[0]+"|"+ msg.getAllRecipients()[0]+"|"+msg.getSentDate()+"|"+ msg.getSubject()+"|"+msg.getSize()+"]";
			
			log(logMsg);
			
			if (!ADMIN.equalsIgnoreCase(msg.getFrom()[0].toString())){
				
				MimeMessage messageAEnvoyer = smtpManager.createMessage();
				messageAEnvoyer.setRecipient(RecipientType.TO, msg.getFrom()[0]);
				messageAEnvoyer.setFrom(new InternetAddress(ADMIN));
				messageAEnvoyer.setText("Votre mail est bien arrivé sur la boite de " + msg.getRecipients(RecipientType.TO)[0].toString() +
						 " a " + sdf.format(new Date()) + ".\n Le contenu a été classé dans Alfresco sous la réference:");
				
				log("envoi message [to="+messageAEnvoyer.getRecipients(RecipientType.TO).toString()+ "]");
				smtpManager.sendMail(messageAEnvoyer);
				
				String to =null ;
				if (msg.getFrom()[0].toString().contains("didier") ||msg.getFrom()[0].toString().contains("forget") ){
					to="0033660215004";
				}else if (msg.getFrom()[0].toString().contains("gilbert")){
					to="0033684225978";
				}
				// commente pour test a decommenter
				smsManager.sendMessage("0033660215004", to, "Un mail de la part de " + msg.getFrom()[0] + " vient de vous parvenir. Sujet:"+ mail.getMessage().getSubject());
			}
//			MimeMessage mm = mail.getMessage();
//			InputStream is = mm.getInputStream();
//			byte b[] = new byte[is.available()];
//			
//			is.read(b);
//			
//			System.out.println(new String (b));
			
			wfm.traiterMail(mail.getMessage());
			
		} catch (NullPointerException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			log("message traite normalement");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		
//		try {
//			ClientWSDepot clientDepot =  new ClientWSDepot(adsServer, adsServerPort, adsUri);
//			clientDepot.postMessage(mail);
//			// si tout s'est bien passe on annule le mail
//			log("mail correctement traite, il n'est pas envoy� dans la boite au lettre. id du mail: "+  mail.getName());
//			if (!saveMessages) {
//				// dans ce cas les mail ne sont pas mis dans les boites (arret du traitement)
//				mail.setState(Mail.GHOST);
//			}
//		} catch (Throwable e) {
//			log("erreur detecte : " + e.getMessage() + " le mail est rejete. id du mail: " + mail.getName() );
//			mail.setState(Mail.ERROR);
//		}
		
		
	}

}


